<?php
$path_root = $_SERVER['DOCUMENT_ROOT'];
// var_dump($path_root); exit();
//
require($path_root . "/AppSaleOnline/libs/model.php");

class Applications extends Model
{
    public $_display; // so ban ghi can hien thi tren mot trang

    public function __construct()
    {
        parent::__construct(); // call parent construct();
    }
    
    // tra ve ket noi csdl
    public function return_link_connect()
    {
        return $this->_link;
    }
    
    // chen ban ghi vao bang app_user
    public function insert_into_app_user_table($app_id, $user_id, $current_time)
    {
        $sql = "INSERT INTO `app_user`(`app_id`, `user_id`, `time_download`) VALUES($app_id, $user_id, '$current_time')";
        // var_dump($sql); exit();            
        $result = mysqli_query($this->_link, $sql);
        
        if($result == "")
        {
            throw new Exception("Error ".mysqli_error($this->_link)); // phat sinh ra loi neu truy van sai
        } 
        try 
        {
            return true;
        } 
        catch(Exception $e)
        {
            return $e->getMessage();
        }        
    }
    // hien thi chi tiet download ung dung
    public function show_detail_download($app_name)
    {
        $sql = "SELECT A.username,B.app_name, C.time_download FROM app_user C JOIN users A ON A.user_id = C.user_id
        JOIN apps_list B ON B.app_id = C.app_id WHERE B.app_name = '$app_name';
        ";
        // var_dump($sql); exit();
        $result = mysqli_query($this->_link, $sql);
        
        if(mysqli_num_rows($result) > 0)
        {
            $data = array();
            while($rows = mysqli_fetch_array($result, MYSQLI_ASSOC))
            {
                $data[] = $rows;    
            }
            return $data;
        }
        return array(); // neu du lieu khong co tra ve
    }
    // ham lay item cua app theo ID
    public function getItemByID($appID)
    {
        $sql = "Select * From apps_list Where app_id = $appID Order By app_id ASC";
        // thuc hien cau truy van
        $result = mysqli_query($this->_link, $sql);
        // lay du lieu
        $data = mysqli_fetch_array($result, MYSQLI_ASSOC);
        // tra ve du lieu voi $data vua lay o tren
        return $data;
    }

    // xoa mot ung dung void ID nhap vao
    public function delete_Item_By_Id($app_id)
    {
        $sql = "Delete From apps_list WHERE `app_id` == $$app_id";

        $result = mysqli_query($this->_link, $sql);

        if($result != null)
            return true;
        return false;
    }

    // lay ra danh sach tat ca san pham
    public function getListApplications()
    {
        $sql = "SELECT * FROM apps_list order by app_id DESC";
        // thuc hien truy van
        $result = mysqli_query($this->_link, $sql);
        $listApp = array();
        if (!$result) {
            throw new Exception("Error ".mysqli_error($this->_link));
        }// neu khong loi xay ra thi thuc hien lenh trong try
        try
        {
            while( $rows = mysqli_fetch_array($result, MYSQLI_ASSOC))
            {
                $listApp[] = $rows;
            }
            return $listApp;
        } catch(Exception $e ) // bat ngoai le xay ra
        {
            return $e->getMessage();
        }
    }

    // loc san pham theo tinh trang la mien phi hoac tra tien
    public function listAppByStatus($status)
    {
        $sql = "SELECT * FROM apps_list WHERE app_status = '$status' order by app_id ASC";
        $result = mysqli_query($this->_link, $sql);
        if (!$result) // if query is empty or error
        {
            throw new Exception("Error query");
        }
        try
        {
            $listApp = array();
            while ($rows = mysqli_fetch_array($result, MYSQLI_ASSOC))
            {
                $listApp[] = $rows;
            }
            return $listApp;
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    // tang luot download cho san pham
    public function increase_number_download($file_name)
    {
        $sql = "Update `apps_list` SET `count_dl` = `count_dl` + 1 WHERE `app_path` = '$file_name'";

        $result = mysqli_query($this->_link, $sql);

        if($result != null)
            return true;
        return false;
    }
    // tim ung dung co luot tai cao nhat trong csdl
    public function find_app_has_number_download_max()
    {
        $sql = "select * from apps_list ORDER BY `count_dl` DESC LIMIT 0,1";
        $result = mysqli_query($this->_link, $sql);
        if($result != null)
        {
            return mysqli_fetch_row($result);
        } else {
            return "";
        }
    }

    // kiem tra san pham co ton tai trong CSDL hay khong
    public function checkAppExists($_id)
    {
        $sql = "Select * from apps_lists Where app_id = $_id order by app_id ASC";
        // thuc thi truy van
        $result = mysqli_query($this->_link, $sql);
        // kiem tra cau truy van
        if (!$result) {
            throw new Exception("Error query!");
            return false;
        }
        try {
            // echo "phan trong try";
            $_numRows = mysqli_num_rows($result);
            // neu so dong tra ve ma lon hoac = 1 ban ghi
            return ($_numRows > 0) ? true : false;
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    public function getDataWithSql($sql)
    {
        $result = mysqli_query($this->_link, $sql);

        if(!$result) {
            echo mysqli_error($this->_link);
        } else {
            $data = array();

            while($rows = mysqli_fetch_array($result, MYSQLI_ASSOC))
            {
                $data[] = $rows;
            }

            return $data;
        }
    }

    // tim kiem ung dung voi keyword nhap vao
    public function search_apps_with_keyword($keyword)
    {
        $sql = "Select * from apps_list Where app_name LIKE '%$keyword%'";

        $result = mysqli_query($this->_link, $sql);

        if(mysqli_num_rows($result) < 0)
        {
            echo "Khong tim thay du lieu nao";
        } else {
            $data = array();

            while($rows = mysqli_fetch_array($result, MYSQLI_ASSOC))
            {
                $data[] = $rows;
            }
            return $data;
        }
    }
    // function them ung dung vao csdl
    public function insert_application_into_table($app_name, $app_status, $app_desc, $app_path)
    {
        $sql = "INSERT INTO apps_list(`app_name`, `app_status`, `app_desc`, `app_path`) VALUES('$app_name', '$app_status', '$app_desc', '$app_path')";
        
        var_dump($sql);
        
        $result = mysqli_query($this->_link, $sql);
        
        $msg = "";
        if($result == null)
        {
            throw new Exception("Error. ".mysqli_error($this->_link));
        }
        try {
            $msg .= "OK them ung dung thanh cong";
        }
        catch (Exception $e)
        {
            return $e->getMessage();
        }
        return $msg;
    }

    // tong so ban ghi cua table
    public function sum_record_from_table($sql)
    {
        $result = mysqli_query($this->_link, $sql);

        if($result != null)
            return mysqli_num_rows($result);
    }

    // phan trang cac ung dung
    public function pagination_application_list($start, $sql)
    {
        // tong so ban ghi la
        $sum_record = $this->sum_record_from_table($sql);

        // tong so tran can phai phan ra la
        $num_pages = ceil($sum_record/ $this->_display);

        // sql voi gioi han phan trang
        $sql .= " LIMIT $start, $this->_display";

        // du lieu sau khi phan ra voi limit truyen vao
        $data = $this->getDataWithSql($sql);

        // hien thi du lieu ra
        echo "<table border='0' class='table table-striped'>";
        echo "<thead>";
            echo "<th>ID</th>";
            echo "<th>Giá</th>";
            echo "<th>Tình trạng</th>";
            echo "<th colspan='2'>Tác vụ</th>";
        echo "</thead>";
        foreach($data as $key => $value)
        {
            $app_Id = $data[$key]['app_id'];
            echo "<tr>";
                echo "<td>".$app_Id."</td>";
                echo "<td>".$data[$key]['app_price']."</td>";
                echo "<td>".$data[$key]['app_status']."</td>";
                echo "<td><a href='?appID=$app_Id&comamnd=Edit'>Edit</a></td>";
                echo "<td><a class=\"del_app\" href='?appID=$app_Id&command=Delete'>Delete</a></td>";
            echo "</tr>";
        }
        echo "</table>";

        // ky thuat phan trang the hien o day
        echo "<div id='pagination'>"; // div pagination
        if($num_pages > 1)
        {
            $next = $start + $this->_display;
            $previous = $start - $this->_display;
            $current_page = $start/ $this->_display + 1;

            if($current_page >= 5)
            {
                $startLoop = $current_page - 2; // bat dau tu trang so 3

                if($num_pages > $current_page + 2)
                {
                    $endLoop = $current_page + 2;
                }

                if($current_page > $num_pages - 4 && $current_page <= $num_pages)
                {
                    $startLoop = $num_pages - 4;
                    $endLoop = $num_pages;
                } else {
                    $endLoop = $num_pages;
                }

            } else {
                $startLoop = 1;

                if($num_pages > 5) {
                    $endLoop = 5;
                } else {
                    $endLoop  = $num_pages;
                }
            }

            // xuat hien trang next
            if($current_page != $num_pages)
            {
                echo "<a href='javascript:void(0)' onclick='gotoPage($next)'>Next</a>";
            }

            // xuat hien so thu tu tung trang
            for($i = $startLoop; $i <= $endLoop; $i++)
            {
                if($i == $current_page)
                {
                    echo "<span class='actived'>".$i."</span>";
                } else {
                    $index_pages = $this->_display*($i - 1);
                    echo "<a href='javascript:void(0)' onclick='gotoPage($index_pages)'>".$i."</a>";
                }
            }

            // hien thi trang previous
            if($current_page > 1 && $current_page <= $num_pages)
            {
                echo "<a href='javascript:void(0)' onclick='gotoPage($previous)'>Previous</a>";
            }

        }
        echo "</div>"; // END div pagination
    }
}


